package org.aphelie.torg.ruler.internal.core.text.character;

import java.util.ArrayList;

import org.aphelie.torg.ruler.core.IModelChangedEvent;
import org.aphelie.torg.ruler.core.character.ICharacterObject;
import org.aphelie.torg.ruler.core.character.ICharacterParent;
import org.aphelie.torg.ruler.internal.core.text.IDocumentElementNode;
import org.eclipse.core.runtime.CoreException;


public class CharacterParentNode extends CharacterObjectNode implements ICharacterParent {

    private static final long serialVersionUID = 1L;

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#add(int, org.eclipse.pde.core.plugin.ICharacterObject)
     */
    public void add(int index, ICharacterObject child) throws CoreException {
        addChildNode((IDocumentElementNode) child, index);
        fireStructureChanged(child, IModelChangedEvent.INSERT);
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#add(org.eclipse.pde.core.plugin.ICharacterObject)
     */
    public void add(ICharacterObject child) throws CoreException {
        add(getChildCount(), child);
        child.setInTheModel(true);
        ((CharacterObjectNode) child).setModel(getModel());
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#getChildCount()
     */
    public int getChildCount() {
        return getChildNodes().length;
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#getIndexOf(org.eclipse.pde.core.plugin.ICharacterObject)
     */
    public int getIndexOf(ICharacterObject child) {
        return indexOf((IDocumentElementNode) child);
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#swap(org.eclipse.pde.core.plugin.ICharacterObject, org.eclipse.pde.core.plugin.ICharacterObject)
     */
    public void swap(ICharacterObject child1, ICharacterObject child2) throws CoreException {
        swap((IDocumentElementNode) child1, (IDocumentElementNode) child2);
        firePropertyChanged(this, P_SIBLING_ORDER, child1, child2);
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#getChildren()
     */
    public ICharacterObject[] getChildren() {
        ArrayList result = new ArrayList();
        IDocumentElementNode[] nodes = getChildNodes();
        for (int i = 0; i < nodes.length; i++)
            result.add(nodes[i]);

        return (ICharacterObject[]) result.toArray(new ICharacterObject[result.size()]);
    }

    /* (non-Javadoc)
     * @see org.eclipse.pde.core.plugin.ICharacterParent#remove(org.eclipse.pde.core.plugin.ICharacterObject)
     */
    public void remove(ICharacterObject child) throws CoreException {
        removeChildNode((IDocumentElementNode) child);
        child.setInTheModel(false);
        fireStructureChanged(child, IModelChangedEvent.REMOVE);
    }
}
